# Authors: Emil & Ivetta

# this script does subgroup conjoint analysis
# beware cjplot package needs categorical variables to be factors, otherwise it doesn't understand

# This script produces following figures and tables
# Figure 3 and 4 in the main text
# Figure 10 in the appendix

pacman::p_load(haven, dplyr, labelled, xlsx, cjoint, sandwich, lmtest, cregg, car, stringr, 
               ggtext, glue, ggsci, patchwork, forcats)
#install.packages("ggstance")

#import conjoint df enriched by all the vars from the second wave survey
df <- read_sav("drafts/conjoint_solidarity/perspectives_docs/revision_2/replication_code/input_data.sav")
df <- as_factor(df)


#setting cool ggtheme
theme_Publication <- function(base_size=18, base_family="Helvetica") {
  library(grid)
  library(ggthemes)
  (theme_foundation(base_size=base_size, base_family=base_family)
    + theme(plot.title = element_text(face = "bold",
                                      size = rel(0.9), hjust = 0.5),
            text = element_text(),
            panel.background = element_rect(colour = NA),
            plot.background = element_rect(colour = NA),
            panel.border = element_rect(colour = NA),
            axis.title = element_text(face = "bold",size = rel(0.8)),
            axis.title.y = element_text(angle=90,vjust =2),
            axis.title.x = element_text(vjust = -0.2),
            axis.text = element_text(), 
            axis.line = element_line(colour="black"),
            axis.ticks = element_line(),
            panel.grid.major = element_line(colour="#f0f0f0"),
            panel.grid.minor = element_blank(),
            legend.key = element_rect(colour = NA),
            legend.position = "bottom",
            legend.direction = "horizontal",
            legend.key.size= unit(0.2, "cm"),
            legend.margin = unit(0, "cm"),
            legend.title = element_text(face="italic"),
            plot.margin=unit(c(10,5,5,5),"mm"),
            strip.background=element_rect(colour="#f0f0f0",fill="#f0f0f0"),
            strip.text = element_text(face="bold")
    ))
  
}



# Define labels to be bold in the plot
bold_labels <- c("Age:", "Gender:", "Children:", "Profession:", "Ethnic background:", "Motivation for emigration:") %>%
  paste0(collapse = "|")

# Custom function to apply bold to specific labels
highlight <- function(x, pat, color="black", family="") {
  # Remove parentheses
  x <- gsub("[()]", "", x)
  
  # Apply bold to labels that match the pattern
  ifelse(grepl(pat, x), glue::glue("<b style='font-family:{family}; color:{color}'>{x}</b>"), x)
}


################################################
################################################
################################################
################################################
# Subgroup analysis
################################################
################################################
################################################
################################################

# Adding a break line for plotting
df_mig <- df %>%
  mutate(Motivation = fct_recode(Motivation,
                                 `Can't accept Russian politics +<br />Was arrested in rallies` = "Can't accept Russian politics +\nWas arrested in rallies"))




# Guilt
# calculate conditional AMCEs for all guilt levels and Regression for continuous Guilt

df_guilt <- df_mig %>%
  filter(when_left %in% "Да") %>% #filter out old emigrants
  select(ResponseId, 
         choice,
         Age, Gender, Children, Profession, Ethnicity, Motivation,
         guilt_bin) %>%
  na.omit() 

guilt_amces <- cj(df_guilt, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                  id = ~ResponseId, 
                  estimate = "amce", 
                  by = ~guilt_bin)

guilt_amces_diff <- cj(df_guilt, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                  id = ~ResponseId, 
                  estimate = "amce_diff", 
                  by = ~guilt_bin)

label_rename <- c(
  Age = "Age:",
  Gender = "Gender:",
  Children = "Children:",
  Profession = "Profession:",
  Ethnicity = "Ethnic background:",
  Motivation = "Motivation for emigration:"
)

guilt_amces$feature <- ifelse(guilt_amces$feature %in% names(label_rename), 
                              label_rename[guilt_amces$feature], 
                              guilt_amces$feature)

guilt_amces_diff$feature <- ifelse(guilt_amces_diff$feature %in% names(label_rename), 
                              label_rename[guilt_amces_diff$feature], 
                              guilt_amces_diff$feature)


guilt_amces <- guilt_amces %>% 
  filter(!feature %in% c("Gender:", "Age:", "Children:", "Profession:"))

guilt_amces_diff <- guilt_amces_diff %>% 
  filter(!feature %in% c("Gender:", "Age:", "Children:", "Profession:")) %>%
  mutate(BY = "Difference")


guilt_many_amce_plot <- plot(rbind(guilt_amces, guilt_amces_diff), size = 2, legend_pos = "none") +
  ggplot2::facet_wrap(~BY, ncol = 5L) + 
  ggplot2::theme_bw() +
  ggplot2::theme(legend.position = "none") + 
  geom_point(size = 2) +
  scale_color_nejm() +
  scale_y_discrete(labels= function(x) highlight(x, bold_labels, "black")) +
  theme(axis.text.y=element_markdown(),
        axis.ticks.x=element_blank(),
        plot.title = element_text(size = 10)) +
  ggtitle("AMCE Conditional on Respondents’ Group-Based Guilt for Russian Aggression")

# # saving plot
# ggsave("drafts/conjoint_solidarity/plots/main_hetero/guilt_amce_plot.png",
#        guilt_many_amce_plot,
#        dpi = 500,
#        width = 5,
#        height = 5.5)





# Responsibility

# calculate conditional AMCEs for all guilt levels

df_responsiblity <- df_mig %>%
  filter(when_left %in% "Да") %>% #filter out old emigrants
  select(ResponseId, 
         choice,
         Age, Gender, Children, Profession, Ethnicity, Motivation,
         responsiblity_bin) %>%
  na.omit() 

resp_amces <- cj(df_responsiblity, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                 id = ~ResponseId, 
                 estimate = "amce", 
                 by = ~responsiblity_bin)

resp_amces_diff <- cj(df_responsiblity, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                 id = ~ResponseId, 
                 estimate = "amce_diff", 
                 by = ~responsiblity_bin)

label_rename <- c(
  Age = "Age:",
  Gender = "Gender:",
  Children = "Children:",
  Profession = "Profession:",
  Ethnicity = "Ethnic background:",
  Motivation = "Motivation for emigration:"
)

resp_amces$feature <- ifelse(resp_amces$feature %in% names(label_rename), 
                             label_rename[resp_amces$feature], 
                             resp_amces$feature)
resp_amces_diff$feature <- ifelse(resp_amces_diff$feature %in% names(label_rename), 
                             label_rename[resp_amces_diff$feature], 
                             resp_amces_diff$feature)

resp_amces <- resp_amces %>% 
  filter(!feature %in% c("Gender:", "Age:", "Children:", "Profession:"))

resp_amces_diff <- resp_amces_diff %>% 
  filter(!feature %in% c("Gender:", "Age:", "Children:", "Profession:")) %>%
  mutate(BY = "Difference")



resp_many_amce_plot <- plot(rbind(resp_amces, resp_amces_diff), size = 2, legend_pos = "none") + 
  ggplot2::facet_wrap(~BY, ncol = 5L) + 
  geom_point(size = 2) +
  scale_color_nejm() +
  scale_y_discrete(labels= function(x) highlight(x, bold_labels, "black")) +
  ggplot2::theme_bw() +
  ggplot2::theme(legend.position = "none")  + 
  theme(plot.title = element_text(size = 10),
        axis.text.y=element_markdown(),
        axis.ticks.x=element_blank()) +
  ggtitle("AMCE Conditional on Respondents’ Group-Based Responsibility for Russian Aggression")

p_hetero_guilt_resp <- guilt_many_amce_plot / resp_many_amce_plot

# # saving responsiblity plot
# ggsave("drafts/conjoint_solidarity/plots/main_hetero/resp_amce_plot.png",
#        resp_many_amce_plot,
#        dpi = 500,
#        width = 5, height = 5.5)



# saving plot
ggsave("drafts/conjoint_solidarity/plots/main_hetero/amce_hetero_guilt_resp.png",
       p_hetero_guilt_resp,
       dpi = 500,
       width = 8,
       height = 6)


# Political and Civic Activism

# calculate conditional AMCEs for all guilt levels

df_activ <- df_mig %>%
  filter(when_left %in% "Да") %>% #filter out old emigrants
  select(ResponseId, 
         choice,
         Age, Gender, Children, Profession, Ethnicity, Motivation,
         polit_civic_bin) %>%
  na.omit()

activ_amces <- cj(df_activ, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                  id = ~ResponseId, 
                  estimate = "amce", 
                  by = ~polit_civic_bin)


activ_amces_diff <- cj(df_activ, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                  id = ~ResponseId, 
                  estimate = "amce_diff", 
                  by = ~polit_civic_bin)

label_rename <- c(
  Age = "Age:",
  Gender = "Gender:",
  Children = "Children:",
  Profession = "Profession:",
  Ethnicity = "Ethnic background:",
  Motivation = "Motivation for emigration:"
)

activ_amces$feature <- ifelse(activ_amces$feature %in% names(label_rename), 
                              label_rename[activ_amces$feature], 
                              activ_amces$feature)

activ_amces_diff$feature <- ifelse(activ_amces_diff$feature %in% names(label_rename), 
                              label_rename[activ_amces_diff$feature], 
                              activ_amces_diff$feature)


activ_amces <- activ_amces %>% 
  filter(!feature %in% c("Gender:", "Age:", "Children:", "Profession:"))

activ_amces_diff <- activ_amces_diff %>% 
  filter(!feature %in% c("Gender:", "Age:", "Children:", "Profession:")) %>%
  mutate(BY = "Difference")


active_many_amce_plot <- plot(rbind(activ_amces, activ_amces_diff), size = 2, legend_pos = "none") + 
  ggplot2::facet_wrap(~BY, ncol = 5L) + 
  ggplot2::theme_bw() +
  ggplot2::theme(legend.position = "none") + 
  geom_point(size = 2) +
  scale_color_nejm() +
  scale_y_discrete(labels= function(x) highlight(x, bold_labels, "black")) +
  theme(axis.text.y=element_markdown(),
        axis.ticks.x=element_blank(),
        plot.title = element_text(size = 10)) +
  ggtitle("AMCE Conditional on Respondents’ Political Engagement")



# Political interest

df_activ <- df_mig %>%
  filter(when_left %in% "Да") %>% #filter out old emigrants
  select(ResponseId, 
         choice,
         Age, Gender, Children, Profession, Ethnicity, Motivation,
         politics_interest_bin) %>%
  na.omit()

activ_amces <- cj(df_activ, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                  id = ~ResponseId, 
                  estimate = "amce", 
                  by = ~politics_interest_bin)


activ_amces_diff <- cj(df_activ, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                       id = ~ResponseId, 
                       estimate = "amce_diff", 
                       by = ~politics_interest_bin)

label_rename <- c(
  Age = "Age:",
  Gender = "Gender:",
  Children = "Children:",
  Profession = "Profession:",
  Ethnicity = "Ethnic background:",
  Motivation = "Motivation for emigration:"
)

activ_amces$feature <- ifelse(activ_amces$feature %in% names(label_rename), 
                              label_rename[activ_amces$feature], 
                              activ_amces$feature)

activ_amces_diff$feature <- ifelse(activ_amces_diff$feature %in% names(label_rename), 
                                   label_rename[activ_amces_diff$feature], 
                                   activ_amces_diff$feature)


activ_amces <- activ_amces %>% 
  filter(!feature %in% c("Gender:", "Age:", "Children:", "Profession:"))

activ_amces_diff <- activ_amces_diff %>% 
  filter(!feature %in% c("Gender:", "Age:", "Children:", "Profession:")) %>%
  mutate(BY = "Difference")


interest_many_amce_plot <- plot(rbind(activ_amces, activ_amces_diff), size = 2, legend_pos = "none") + 
  ggplot2::facet_wrap(~BY, ncol = 5L) + 
  ggplot2::theme_bw() +
  ggplot2::theme(legend.position = "none") + 
  geom_point(size = 2) +
  scale_color_nejm() +
  scale_y_discrete(labels= function(x) highlight(x, bold_labels, "black")) +
  theme(axis.text.y=element_markdown(),
        axis.ticks.x=element_blank(),
        plot.title = element_text(size = 10)) +
  ggtitle("AMCE Conditional on Respondents’ Political Interest")



p_hetero_active <- active_many_amce_plot / interest_many_amce_plot



# saving plot
ggsave("drafts/conjoint_solidarity/plots/main_hetero/amce_hetero_active.png",
       p_hetero_active,
       dpi = 500,
       width = 8,
       height = 6)




# Discrimination aggregate (country)

df_disc_agg <- df_mig %>%
  filter(when_left %in% "Да") %>% #filter out old emigrants
  filter(!is.na(discrimination_soc)) %>%
  group_by(country_now_merged) %>%
  dplyr::summarise(disc = mean(as.numeric(as.character(discrimination_soc)), na.rm = TRUE),
                   n_resp = n()) %>%
  filter(n_resp > 30)

# Top 5 countries with highest social discrimination: Georgia, Poland, Latvia, Lithuania, France (source: https://outrush.io/maps_difficulties_123)


df_disc_country <- df_mig %>%
  filter(when_left %in% "Да") %>% #filter out old emigrants
  mutate(disc_country = factor(case_when(country_now_merged %in% c("Грузия", "Польша", "Латвия", "Литва", "Франция")  ~ "1. High discrimination",
                                         !country_now_merged %in% c("Грузия", "Польша", "Латвия", "Литва", "Франция")  ~ "0. Low discrimination"))) %>%
  select(ResponseId, 
         choice,
         Age, Gender, Children, Profession, Ethnicity, Motivation,
         disc_country,
         country_now_merged) %>%
  na.omit() 


table(df_disc_country$country_now_merged, df_disc_country$disc_country)

disc_amces <- cj(df_disc_country, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                 id = ~ResponseId, 
                 estimate = "amce", 
                 by = ~disc_country)

disc_amces_diff <- cj(df_disc_country, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                      id = ~ResponseId, 
                      estimate = "amce_diff", 
                      by = ~disc_country)


label_rename <- c(
  Age = "Age:",
  Gender = "Gender:",
  Children = "Children:",
  Profession = "Profession:",
  Ethnicity = "Ethnic background:",
  Motivation = "Motivation for emigration:"
)

# eliminate for visualization purposes age, children, gender


disc_amces$feature <- ifelse(disc_amces$feature %in% names(label_rename), 
                             label_rename[disc_amces$feature], 
                             disc_amces$feature)


disc_amces_diff$feature <- ifelse(disc_amces_diff$feature %in% names(label_rename), 
                                  label_rename[disc_amces_diff$feature], 
                                  disc_amces_diff$feature)

disc_amces <- disc_amces %>% 
  filter(!feature %in% c("Gender:", "Age:", "Children:", "Profession:"))

disc_amces_diff <- disc_amces_diff %>% 
  filter(!feature %in% c("Gender:", "Age:", "Children:", "Profession:")) %>%
  mutate(BY = "Difference")

disc_many_amce_plot <- plot(rbind(disc_amces, disc_amces_diff), size = 2, legend_pos = "none") + 
  ggplot2::facet_wrap(~BY, ncol = 5L) + 
  ggplot2::theme_bw() +
  ggplot2::theme(legend.position = "none")  + 
  geom_point(size = 2) +
  scale_color_nejm() +
  scale_y_discrete(labels= function(x) highlight(x, bold_labels, "black")) +
  theme(axis.text.y=element_markdown(),
        axis.ticks.x=element_blank(),
        plot.title = element_text(size = 10)) +
  ggtitle("AMCE Conditional on Level of Discrimination in Host-Country")

disc_many_amce_plot


# saving plot
ggsave("drafts/conjoint_solidarity/plots/main_hetero/amce_hetero_active_disc.png",
       p_hetero_active_disc,
       dpi = 500,
       width = 8,
       height = 6)



# latex table
disc_amces_tab <- disc_amces_diff %>%
  select(-BY,-outcome,-statistic,-disc_country,-lower,-upper)

library(kableExtra)
disc_amces_tab_latex <- disc_amces_tab %>%
  mutate(
    feature = gsub("Age:", "Age", feature),
    feature = gsub("Children:", "Children", feature),
    feature = gsub("Ethnic background:", "Ethnicity", feature),
    feature = gsub("Gender:", "Gender", feature),
    feature = gsub("Motivation for emigration:", "Motivation", feature),
    feature = gsub("Profession:", "Profession", feature),
    estimate = round(estimate, 3),
    std.error = round(std.error, 3),
    z = round(z, 3),
    p = round(p, 3)
  ) %>%
  kable("latex", booktabs = TRUE, linesep = "", caption = "AMCE Differences Between Countries With High and Low Discrimination", 
        label = "tab:cis_amce", align = c("l", "l", "r", "r", "r", "r")) %>%
  kable_styling(latex_options = c("HOLD_position", "scale_down")) %>% 
  footnote(
    general = "AMCE Differences between countries with the highest levels of discrimination and others. Countries with the highest levels of discriminationare defined as those with the highest reported discrimination from locals, and include Georgia, Poland, Latvia, Lithuania, and France",
    general_title = "",
    footnote_as_chunk = TRUE,
    escape = FALSE
  )


disc_amces_tab_latex




# Host country  difference
df_country_top <- df_mig %>%
  filter(when_left %in% "Да") %>% #filter out old emigrants
  select(ResponseId, 
         choice,
         Age, Gender, Children, Profession, Ethnicity, Motivation, 
         country_top) %>%
  na.omit()


#amces subgroups by country difference
amce_country <- cj(df_country_top, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, id = ~ResponseId, estimate = "amce", 
              by = ~country_top)

label_rename <- c(
  Age = "Age:",
  Gender = "Gender:",
  Children = "Children:",
  Profession = "Profession:",
  Ethnicity = "Ethnic background:",
  Motivation = "Motivation for emigration:"
)

amce_country$feature <- ifelse(amce_country$feature %in% names(label_rename), 
                                label_rename[amce_country$feature], 
                               amce_country$feature)


amce_country_plot <- plot(rbind(amce_country), size = 2, legend_pos = "none") + 
  ggplot2::facet_wrap(~BY, ncol = 3L) + 
  ggplot2::theme_bw() +
  ggplot2::theme(legend.position = "none")  + 
  geom_point(size = 2) +
  scale_color_nejm() +
  scale_y_discrete(labels= function(x) highlight(x, bold_labels, "black")) +
  theme(axis.text.y=element_markdown())

ggsave("drafts/conjoint_solidarity/plots/main_plots/country_top.png",
       amce_country_plot,
       dpi = 500,
       width = 7, height = 8.5)






# Country neighbours and CIS

# calculate conditional AMCEs for all guilt levels

table(df_mig$country_english[df_mig$country_cis %in% "CIS country"])

df_cis <- df_mig %>%
  filter(when_left %in% "Да") %>% #filter out old emigrants
  select(ResponseId, 
         choice,
         Age, Gender, Children, Profession, Ethnicity, Motivation,
         country_cis) %>%
  mutate() %>%
  na.omit() 

cis_amces <- cj(df_cis, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                    id = ~ResponseId, 
                    estimate = "amce_diff", 
                    by = ~country_cis)


label_rename <- c(
  Age = "Age:",
  Gender = "Gender:",
  Children = "Children:",
  Profession = "Profession:",
  Ethnicity = "Ethnic background:",
  Motivation = "Motivation for emigration:"
)

cis_amces$feature <- ifelse(cis_amces$feature %in% names(label_rename), 
                                label_rename[cis_amces$feature], 
                            cis_amces$feature)


cis_amces_plot <- plot(rbind(cis_amces), size = 2, legend_pos = "none") + 
  ggplot2::facet_wrap(~BY, ncol = 5L) + 
  ggplot2::theme_bw() +
  ggplot2::theme(legend.position = "none")  + 
  geom_point(size = 2) +
  scale_color_nejm() +
  scale_y_discrete(labels= function(x) highlight(x, bold_labels, "black")) +
  theme(axis.text.y=element_markdown(),
        axis.ticks.x=element_blank(),
        plot.title = element_text(size = 8)) +
  ggtitle("AMCE Differences Between Countries in the Commonwealth of Independent States (CIS) \nand Those Outside It")


ggsave("drafts/conjoint_solidarity/plots/main_hetero/countries_cis.png",
       cis_amces_plot,
       dpi = 500,
       width = 7, height = 5)

# latex table
cis_tab <- cis_amces %>%
  select(-BY,-outcome,-statistic,-country_cis,-lower,-upper)

library(kableExtra)
cis_tab_latex <- cis_tab %>%
  mutate(
    feature = gsub("Age:", "Age", feature),
    feature = gsub("Children:", "Children", feature),
    feature = gsub("Ethnic background:", "Ethnicity", feature),
    feature = gsub("Gender:", "Gender", feature),
    feature = gsub("Motivation for emigration:", "Motivation", feature),
    feature = gsub("Profession:", "Profession", feature),
    estimate = round(estimate, 3),
    std.error = round(std.error, 3),
    z = round(z, 3),
    p = round(p, 3)
  ) %>%
  kable("latex", booktabs = TRUE, linesep = "", caption = "AMCE Differences Between Countries in the Commonwealth of Independent States (CIS) \nand Those Outside It.", 
        label = "tab:cis_amce", align = c("l", "l", "r", "r", "r", "r")) %>%
  kable_styling(latex_options = c("HOLD_position", "scale_down")) %>%
  footnote(
    general = "Commonwealth of Independent States includes: Armenia, Azerbaijan, Belarus, Kazakhstan, Kyrgyzstan, Moldova, Uzbekistan",
    general_title = "",
    footnote_as_chunk = TRUE,
    escape = FALSE
  )


table(df_mig$country_english[df_mig$country_neighbours %in% "Shared border"])

df_neighbour <- df_mig %>%
  filter(when_left %in% "Да") %>% #filter out old emigrants
  select(ResponseId, 
         choice,
         Age, Gender, Children, Profession, Ethnicity, Motivation,
         country_neighbours) %>%
  na.omit() 

neighbours_amces <- cj(df_neighbour, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                id = ~ResponseId, 
                estimate = "amce_diff", 
                by = ~country_neighbours)


label_rename <- c(
  Age = "Age:",
  Gender = "Gender:",
  Children = "Children:",
  Profession = "Profession:",
  Ethnicity = "Ethnic background:",
  Motivation = "Motivation for emigration:"
)

neighbours_amces$feature <- ifelse(neighbours_amces$feature %in% names(label_rename), 
                            label_rename[neighbours_amces$feature], 
                            neighbours_amces$feature)


neighbours_amces_plot <- plot(rbind(neighbours_amces), size = 2, legend_pos = "none") + 
  ggplot2::facet_wrap(~BY, ncol = 5L) + 
  ggplot2::theme_bw() +
  ggplot2::theme(legend.position = "none")  + 
  geom_point(size = 2) +
  scale_color_nejm() +
  scale_y_discrete(labels= function(x) highlight(x, bold_labels, "black")) +
  theme(axis.text.y=element_markdown(),
        axis.ticks.x=element_blank(),
        plot.title = element_text(size = 8)) +
  ggtitle("AMCE Differences Between Countries With and Without a Shared Border With Russia")

plots_countries_add <- cis_amces_plot / neighbours_amces_plot

ggsave("drafts/conjoint_solidarity/plots/main_hetero/countries_shared_border.png",
       neighbours_amces_plot,
       dpi = 500,
       width = 7, height = 5)


# latex table
neighbours_tab <- neighbours_amces %>%
  select(-BY,-outcome,-statistic,-country_neighbours,-lower,-upper)

library(kableExtra)
neighbours_tab_latex <- neighbours_tab %>%
  mutate(
    feature = gsub("Age:", "Age", feature),
    feature = gsub("Children:", "Children", feature),
    feature = gsub("Ethnic background:", "Ethnicity", feature),
    feature = gsub("Gender:", "Gender", feature),
    feature = gsub("Motivation for emigration:", "Motivation", feature),
    feature = gsub("Profession:", "Profession", feature),
    estimate = round(estimate, 3),
    std.error = round(std.error, 3),
    z = round(z, 3),
    p = round(p, 3)
  ) %>%
  kable("latex", booktabs = TRUE, linesep = "", caption = "AMCE Differences Between Countries With and Without a Shared Border With Russia", 
        label = "tab:cis_amce", align = c("l", "l", "r", "r", "r", "r")) %>%
  kable_styling(latex_options = c("HOLD_position", "scale_down")) %>% 
  footnote(
    general = "Countries with a shared border with Russia include: Azerbaijan, Belarus, China, Estonia, Finland, Georgia, Kazakhstan, Latvia, Lithuania, Norway, Poland, Ukraine",
    general_title = "",
    footnote_as_chunk = TRUE,
    escape = FALSE
  )



# allied countries excluded

table(df_mig$country_english[df_mig$country_neighbours_no_allies %in% "Shared border"])

df_neighbour_no <- df_mig %>%
  filter(when_left %in% "Да") %>% #filter out old emigrants
  select(ResponseId, 
         choice,
         Age, Gender, Children, Profession, Ethnicity, Motivation,
         country_neighbours_no_allies) %>%
  na.omit() 

neighbours_no_amces <- cj(df_neighbour_no, choice ~ Age + Gender + Children + Profession + Ethnicity + Motivation, 
                       id = ~ResponseId, 
                       estimate = "amce_diff", 
                       by = ~country_neighbours_no_allies)


label_rename <- c(
  Age = "Age:",
  Gender = "Gender:",
  Children = "Children:",
  Profession = "Profession:",
  Ethnicity = "Ethnic background:",
  Motivation = "Motivation for emigration:"
)

neighbours_no_amces$feature <- ifelse(neighbours_no_amces$feature %in% names(label_rename), 
                                   label_rename[neighbours_no_amces$feature], 
                                   neighbours_no_amces$feature)


neighbours_no_amces_plot <- plot(rbind(neighbours_no_amces), size = 2, legend_pos = "none") + 
  ggplot2::facet_wrap(~BY, ncol = 5L) + 
  ggplot2::theme_bw() +
  ggplot2::theme(legend.position = "none")  + 
  geom_point(size = 2) +
  scale_color_nejm() +
  scale_y_discrete(labels= function(x) highlight(x, bold_labels, "black")) +
  theme(axis.text.y=element_markdown(),
        axis.ticks.x=element_blank(),
        plot.title = element_text(size = 8)) +
  ggtitle("AMCE Differences Between Countries With and Without a Shared Border With Russia
          Allied Countries Excluded: Azerbaijan, Belarus, Kazakhstan and China")


plots_countries_add <- cis_amces_plot / neighbours_amces_plot / neighbours_no_amces_plot

# saving responsiblity plot
ggsave("drafts/conjoint_solidarity/plots/main_hetero/countries_shared_border_no_allies.png",
       neighbours_no_amces_plot,
       dpi = 500,
       width = 7, height = 5)

table(df_mig$country_neighbours, df_mig$country_english)


# latex table
neighbours_no_tab <- neighbours_no_amces %>%
  select(-BY,-outcome,-statistic,-country_neighbours_no_allies,-lower,-upper)

library(kableExtra)
neighbours_no_tab_latex <- neighbours_no_tab %>%
  mutate(
    feature = gsub("Age:", "Age", feature),
    feature = gsub("Children:", "Children", feature),
    feature = gsub("Ethnic background:", "Ethnicity", feature),
    feature = gsub("Gender:", "Gender", feature),
    feature = gsub("Motivation for emigration:", "Motivation", feature),
    feature = gsub("Profession:", "Profession", feature),
    estimate = round(estimate, 3),
    std.error = round(std.error, 3),
    z = round(z, 3),
    p = round(p, 3)
  ) %>%
  kable("latex", booktabs = TRUE, linesep = "", caption = "AMCE Differences Between Countries With and Without a Shared Border With Russia
          Allied Countries Excluded: Azerbaijan, Belarus, Kazakhstan and China", 
        label = "tab:cis_amce", align = c("l", "l", "r", "r", "r", "r")) %>%
  kable_styling(latex_options = c("HOLD_position", "scale_down")) %>% 
  footnote(
    general = "Countries with a shared border with Russia include: Estonia, Finland, Georgia, Latvia, Lithuania, Norway, Poland, Ukraine.  Allied Countries Excluded: Azerbaijan, Belarus, Kazakhstan and China.",
    general_title = "",
    footnote_as_chunk = TRUE,
    escape = FALSE
  )


